#include "srmainwindow.h"

#include <ctime>
#include <iostream>

#include <QDateTime>
#include <QMessageBox>
#include <QApplication>
#include <QVBoxLayout>
#include <QShowEvent>
#include <QPushButton>
#include <QDebug>
#include <QDir>
#include <QScrollArea>
#include <QScrollBar>

#include "page/srregisterpage.h"
#include "page/srloginpage.h"
#include "page/srbusinesspage.h"
#include "page/oewalletselectwidget.h"
//#include "page/srcreatewallet.h"
#include "page/oeregisterpage.h"

#include "page/subpage/forgetpswdpage/demoforgetissuewidget.h"

#include <OECommonHelper>
#include <OESystemTrayIcon>
#include <OECommonHelper>
#include "qxt/qxtglobalshortcut.h"

// private library
#include <auditcore.h>
#include <auditapi.h>



SRMainWindow::SRMainWindow(QWidget *parent)
    : OEFramelessWindow(parent),lastWidget_(Q_NULLPTR),
        isMainWindow_(0),firstLogin_(0),registerMode_(0){
    setWindowFlags(Qt::FramelessWindowHint);
//    setWindowIcon(QIcon(":/ico/logo"));
    setWindowTitle(tr("币宝"));

    if (!QDir("wallet").exists())
        QDir("wallet").mkdir("wallet");
    QDir::setCurrent("wallet");

    resize(1024,768);
//    CommonHelper::moveCenter(this);

    QxtGlobalShortcut* shortcut = new QxtGlobalShortcut(
                            QKeySequence("Ctrl+Alt+Z"), this);

    connect(shortcut, SIGNAL(activated()),
            this, SLOT(onShortcutShow()));

//    onBusiness("asd","asdd");
    onLogin();
}

SRMainWindow::~SRMainWindow(void) {
}

void SRMainWindow::start(void) {
    // 验证本机是否已经注册
//    int ret = apiCheckRegistered();

    trayIcon_ = OESystemTrayIcon::instance(this);
    trayIcon_->setTray(tr("币宝"),":/ico/logo",
                   tr("双击这里显示操作界面"));
    // 显示托盘
    trayIcon_->showTray();

//    if (0 != ret) {
//        onRegister();
//    }
//    else {
//        onLogin();
//    }
}

//重写鼠标按下事件
void SRMainWindow::mousePressEvent(QMouseEvent *event)
{
    if (!bIsMoveing_)
        return;
    bMoveing_ = true;
    //记录下鼠标相对于窗口的位置
    //event->globalPos()鼠标按下时，鼠标相对于整个屏幕位置
    //pos() this->pos()鼠标按下时，窗口相对于整个屏幕位置
    movePosition_ = event->globalPos() - pos();

    return QMainWindow::mousePressEvent(event);
}

//重写鼠标移动事件
void SRMainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (!bIsMoveing_)
        return;
    if (movePosition_.isNull()) {
        movePosition_ = event->globalPos() - pos();
    }
    //(event->buttons() && Qt::LeftButton)按下是左键
    //鼠标移动事件需要移动窗口，窗口移动到哪里呢？就是要获取鼠标移动中，窗口在整个屏幕的坐标，然后move到这个坐标，怎么获取坐标？
    //通过事件event->globalPos()知道鼠标坐标，鼠标坐标减去鼠标相对于窗口位置，就是窗口在整个屏幕的坐标
    if (bMoveing_ && (event->buttons() && Qt::LeftButton)
        && (event->globalPos()-movePosition_).manhattanLength() > QApplication::startDragDistance())
    {
        move(event->globalPos()-movePosition_);
        movePosition_ = event->globalPos() - pos();
    }
    return QMainWindow::mouseMoveEvent(event);
}

void SRMainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    if (!bIsMoveing_)
        return;
    bMoveing_ = false;
}

void SRMainWindow::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    apiLogoutAccount();
    hide();
}


void SRMainWindow::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
}

void SRMainWindow::onShortcutShow() {
    static int time = 0;
    if ((time) < std::time(Q_NULLPTR)) {
        if (this->isHidden()) {
            this->show();
            this->raise();
        }
        else
            this->hide();
        time = std::time(Q_NULLPTR);
    }
}

bool SRMainWindow::onDelDir(const QString &_path)
{
    if (_path.isEmpty()){
        return false;
    }
    QDir dir(_path);
    if(!dir.exists()){
        return true;
    }
    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); //设置过滤
    QFileInfoList fileList = dir.entryInfoList(); // 获取所有的文件信息
    for(auto file : fileList){ //遍历文件信息
        if (file.isFile()){ // 是文件，删除
            file.dir().remove(file.fileName());
        }else{ // 递归删除
            onDelDir(file.absoluteFilePath());
        }
    }
    return dir.rmpath(dir.absolutePath()); // 删除文件夹
}
//void SRMainWindow::onSelectWallet()
//{
//    hide();
//    if (!QDir("wallet").exists())
//        QDir("wallet").mkdir("wallet");
//    QDir::setCurrent("wallet");

//    QVBoxLayout* layout = new QVBoxLayout;
//    QPushButton* btn_close = new QPushButton("Χ");
//    btn_close->setFixedSize(40,40);
//    btn_close->setObjectName("CloseButton");

//    layout->addWidget(btn_close,0,Qt::AlignLeft);
//    layout->setMargin(0);

//    QWidget* widget = new QWidget;
//    widget->setLayout(layout);
//    QScrollArea* scroll_ = new QScrollArea();
//    lastWidget_ = scroll_;
//    OEWalletSelectWidget* wallet= new OEWalletSelectWidget();
//    wallet->loadWallet(QDir::currentPath());
//    layout->addWidget(wallet,0,Qt::AlignHCenter | Qt::AlignTop);
//    scroll_->setWindowFlags(Qt::FramelessWindowHint);
//    scroll_->setWidget(widget);
//    scroll_->show();
//    scroll_->horizontalScrollBar()->hide();
//    connect(btn_close, &QPushButton::clicked,
//            this, &SRMainWindow::close);
//    connect(btn_close, &QPushButton::clicked,
//            scroll_, &QScrollArea::close);
////    hide();
//    setCentralWidget(scroll_);
////    resize(wallet->width()+2,wallet->height()+2);
////    scroll->setFixedSize(322,672);

//    resize(300,450);
//    setFixedWidth(300);

//    // modify wallet name
//    connect(wallet, &OEWalletSelectWidget::sigWalletNameChange,
//            this, [=](const QString&, const QString&){
//        wallet->loadWallet(QDir::currentPath());
//    });
//    // create wallet
//    connect(wallet, &OEWalletSelectWidget::sigCreate,
//            this, &SRMainWindow::onCreateWallet);
//    // enter wallet
//    connect(wallet, &OEWalletSelectWidget::sigFinshed,
//            this, [=]{
//        if (0 != apiInit()) {
//            qWarning("apiInit error..");
//        }
//        setMaximumWidth(9999);
//        initLogin();
//        start();
//        this->show();
//    });
//    // delete wallet
//    connect(wallet, &OEWalletSelectWidget::sigDelete,
//            this, [=](const QString& _name, const QString& _path){
//        int ret = QMessageBox::question(this, "删除钱包",
//                                        QString("是否确认删除\"%1钱包\"？<br>删除后该钱包的本地数据将会移除!")
//                                        .arg(_name),
//                                        QMessageBox::Yes|QMessageBox::No);
//        if (ret == QMessageBox::Yes){
//            onDelDir(_path);
//            wallet->loadWallet(QDir::currentPath());
//            resize(wallet->width()+3,wallet->height()+16);
//        }

//    });
//    // backup wallet
//    connect(wallet, &OEWalletSelectWidget::sigBackup,
//            this, [=](const QString& _srcPath, const QString& _destPath){
//        copyDir(_srcPath,_destPath,true);
//        wallet->loadWallet(QDir::currentPath());
//    });
//    // restore wallet from folder
//    connect(wallet, &OEWalletSelectWidget::sigRestoreFromFolder,
//            this, [=](const QString& _path){
//        QString file_path = QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz");
//        QDir(QDir::currentPath()).mkdir(file_path);
//        copyDir(_path, file_path, true);
//        wallet->loadWallet(QDir::currentPath());
//    });
//    // restore wallet from cryptolalia
//    connect(wallet, &OEWalletSelectWidget::sigRestoreFromCryptolalia,
//            this, [=]{
//        registerMode_ = 1;
//        onCreateWallet();
//    });

//    showNormal();
//}


//bool SRMainWindow::copyDir(const QString &_srcPath,
//                             const QString &_destDir,
//                             bool coverFileIfExist)
//{
//    QDir sourceDir(_srcPath);
//    QDir targetDir(_destDir);
//    if(!targetDir.exists()){    /**< 如果目标目录不存在，则进行创建 */
//        if(!targetDir.mkdir(targetDir.absolutePath()))
//            return false;
//    }

//    QFileInfoList fileInfoList = sourceDir.entryInfoList();
//    foreach(QFileInfo fileInfo, fileInfoList){
//        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
//            continue;

//        if(fileInfo.isDir()){    /**< 当为目录时，递归的进行copy */
//            if(!copyDir(fileInfo.filePath(),
//                targetDir.filePath(fileInfo.fileName()),
//                coverFileIfExist))
//                return false;
//        }
//        else{            /**< 当允许覆盖操作时，将旧文件进行删除操作 */
//            if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
//                targetDir.remove(fileInfo.fileName());
//            }

//            /// 进行文件copy
//            if(!QFile::copy(fileInfo.filePath(),
//                targetDir.filePath(fileInfo.fileName()))){
//                    return false;
//            }
//        }
//    }
//    return true;
//}

//void SRMainWindow::onCreateWallet(void)
//{
//    hide();
//    setMaximumWidth(9999);
//    resize(587,432);
//    if (firstLogin_ == 0) {
//        initLogin();
//    }


//    isMainWindow_ = 0;
//    SRCreateWallet* page = new SRCreateWallet();
//    if (lastWidget_ != Q_NULLPTR) {
//        lastWidget_->hide();
//        layout_->removeWidget(lastWidget_);
//        lastWidget_->deleteLater();
//    }


//    layout_->addWidget(page);
//    lastWidget_ = page;
//    connect(page, &SRCreateWallet::sigFinshed,
//            this,[=]{

//        if (lastWidget_ != Q_NULLPTR) {
//            lastWidget_->hide();
//            layout_->removeWidget(lastWidget_);
//            lastWidget_->deleteLater();
//        }

//        if (0 != apiInit()) {
//            qWarning("apiInit error..");
//        }

//        this->start();
//    });
//    showNormal();
//}


void SRMainWindow::onLogin(void) {
    hide();
    bIsMoveing_ = true;
    setMinimumSize(570,430);
    setMaximumSize(600,500);
    isMainWindow_ = 0;
    SRLoginPage* page = new SRLoginPage();
    if (lastWidget_ != Q_NULLPTR) {
        lastWidget_->hide();

        layout_->removeWidget(lastWidget_);
        lastWidget_->deleteLater();
        lastWidget_ = Q_NULLPTR;
    }

    if (!firstLogin_){
        initLogin();
    }

    layout_->addWidget(page,0,Qt::AlignCenter);
    layout_->addStretch();
    lastWidget_ = page;
    connect(page,SIGNAL(sigLoginFinshed(const QString &,const QString &)),
            this,SLOT(onBusiness(const QString &,const QString &)));
    connect(page,SIGNAL(sigRegister()),
            this,SLOT(onRegister()));
    connect(page,&SRLoginPage::sigForgetPswd,
            this,&SRMainWindow::onForgetPswd);
    show();
    this->raise();
}

void SRMainWindow::onRegister(void) {
    hide();
    setMaximumSize(99999,99999);
    resize(620,750);
    isMainWindow_ = 0;
    OERegisterPage* page = new OERegisterPage();
    if (lastWidget_ != Q_NULLPTR) {
        lastWidget_->hide();
        layout_->removeWidget(lastWidget_);
        lastWidget_->deleteLater();
        lastWidget_ = Q_NULLPTR;
        wdgtMainWindow_ = Q_NULLPTR;
        layout_ = Q_NULLPTR;
        firstLogin_ = 0;
    }

    setCentralWidget(page);
    connect(page,SIGNAL(sigRegisterFinshed()),
            this,SLOT(onLogin()));
    show();
}


void SRMainWindow::onForgetPswd()
{
    hide();
    setFixedSize(400,300);
//    bIsMoveing_ = true;
    isMainWindow_ = 0;
    DemoForgetIssueWidget* page = new DemoForgetIssueWidget();
    if (lastWidget_ != Q_NULLPTR) {
        lastWidget_->hide();
        layout_->removeWidget(lastWidget_);
        lastWidget_->deleteLater();
        lastWidget_ = Q_NULLPTR;
        wdgtMainWindow_ = Q_NULLPTR;
        layout_ = Q_NULLPTR;
        firstLogin_ = 0;
    }

    setCentralWidget(page);
    connect(page, &DemoForgetIssueWidget::sigGetBackUser,
            this, [=] {
        this->onLogin();
    });

    show();
}

void SRMainWindow::onBusiness(const QString & _user, const QString & _name) {
    hide();

    if (!QDir(_user).exists())
        QDir(".").mkdir(_user);
    QDir::setCurrent(_user);


    start();
    setMaximumSize(99999,99999);
    resize(930,750);
    SRBusinessPage* page = new SRBusinessPage();
    page->onUserPswdLogin(_user,_name);

    {
        connect(page, &SRBusinessPage::sigCloseClick,
                this, &SRMainWindow::hide);
        connect(page, &SRBusinessPage::sigMinimizeClick,
                this, &SRMainWindow::showMinimized);
        connect(page, &SRBusinessPage::sigLogoutClick,
                this, [=]{
            firstLogin_ = 0;
            QDir::setCurrent("..");
            this->onLogin();
        });
    }

    if (lastWidget_ != Q_NULLPTR) {
        lastWidget_->hide();
        layout_->removeWidget(lastWidget_);
        lastWidget_->deleteLater();
        lastWidget_ = Q_NULLPTR;
        wdgtMainWindow_ = Q_NULLPTR;
        layout_ = Q_NULLPTR;
    }

    setCentralWidget(page);
    isMainWindow_ = 1;
    showNormal();
}

void SRMainWindow::initLogin()
{
    firstLogin_++;
    wdgtMainWindow_ = new QWidget();
    layout_ = new QVBoxLayout();
    btnClose_ = new QPushButton("Χ");
    btnClose_->setFixedSize(40,40);
    btnClose_->setObjectName("CloseButton");

    layout_->setMargin(0);
    layout_->addWidget(btnClose_,0,Qt::AlignRight | Qt::AlignTop);


    wdgtMainWindow_->setLayout(layout_);
//    wdgtMainWindow_->show();

    setCentralWidget(wdgtMainWindow_);


    connect(btnClose_,&QPushButton::clicked,
            this, &SRMainWindow::close);
}




